
import { useReactive } from '.';
import { statePool } from '../compiler/state';
import { uodate } from '../render';
import { isObject, hasOwnProperty, isEqual } from '../shared/utils';

const get = createGetter(),
      set = createSetter();

function createGetter() {
  return function (target, key, receiver) {
    const res = Reflect.get(target, key, receiver);
    console.log('响应式数据获取:' + target[key]);

    if (isObject(res)) return useReactive(res);

    return res
  }
}

function createSetter() {
  return function (target, key, value, receiver) {
    const oldValue = target[key],
          isKeyExist = hasOwnProperty(target, key),
          res = Reflect.set(target, key, value, receiver)

    if (!isKeyExist) { // 添加
      console.log('响应式数据新增:' + value);

      // todo...
    } else if (!isEqual(value, oldValue)) { // 修改
      console.log('响应式数据修改:' + key + '=' + value);
      
      uodate(statePool, key, value);
    }

    return res;
  }
}

const mutableHandler = {
  get,
  set
}

export {
  mutableHandler
}
